<?php
namespace App\Service\Member;

use Illuminate\Support\Facades\DB;

class YihuService extends BaseService
{
    //医护

    //选项
    public function getOption()
    {
        $arys = ['type' => [], 'yytime' => []];
        //医护类型
        $typeOnes = $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('type', 8)
            ->get();
        if (count($typeOnes)) {
            foreach ($typeOnes as $v) {
                $v = (array) $v;
                $arys['type'][] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'detail' => $v['detail'],
                    'icon' => file_exists($v['icon']) ? env('DOMAIN').'/'.$v['icon'] : '',
                ];
            }
        }
        //预约时间
        $arys['yytime'] = $this->getYYtime(0);
        return $arys;
    }

    /**
     * 医生列表
     * @param array $pages【start，limit】
     */
    public function doctorList($pages, $pas)
    {
        $uids = [];
        if (isset($pas['cate_id']) && $pas['cate_id']) {
            $dOnes = $this->dbConn($this->dbDoctor)
                ->where('del', 0)
                ->where('cate_id', $pas['cate_id'])
                ->get();
            if (count($dOnes)) {
                foreach ($dOnes as $v) {
                    if (!in_array($v->uid, $uids)) {
                        $uids[] = $v->uid;
                    }
                }
            }
        }
        if (isset($pas['doc_name']) && $pas['doc_name']) {
            $dOnes = $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('realname', 'like', $pas['doc_name'].'%')
                ->get();
            if (count($dOnes)) {
                foreach ($dOnes as $v) {
                    if (!in_array($v->id, $uids)) {
                        $uids[] = $v->id;
                    }
                }
            }
        }
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('utype', 2);
        if (!empty($uids)) {
            $db = $db->whereIn('id', $uids);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $head = file_exists($v['head']) ? env('DOMAIN').'/'.$v['head'] : '';
            $dOne = (array) $this->dbConn($this->dbDoctor)
                ->where('uid', $v['id'])
                ->first();
            $did = 0;
            $depart_name = '-';
            $work_title_name = '-';
            $price = 0;
            $yiyuan_name = '-';
            if (!empty($dOne)) {
                $did = $dOne['id'];
                $departOne = (array) $this->dbConn($this->dbCate)
                    ->where('id', $dOne['depart'])
                    ->first();
                $touxianOne = (array) $this->dbConn($this->dbCate)
                    ->where('id', $dOne['work_title'])
                    ->first();
//                $configOne = (array) $this->dbConn($this->dbUdSeek)
//                    ->where('del', 0)
//                    ->where('doctor_id', $dOne['id'])
//                    ->first();
                $configOne = (array) $this->dbConn($this->dbConfig)
                    ->where('del', 0)
                    ->where('id', 1)
                    ->first();
                $yiyuanOne = (array) $this->dbConn($this->dbYiyuan)
                    ->where('id', $dOne['hospital'])
                    ->first();
                $depart_name = empty($departOne) ? '-' : $departOne['title'];
                $work_title_name = empty($touxianOne) ? '-' : $touxianOne['title'];
//                $price = empty($configOne) ? '-' : $configOne['price'];
                $price = empty($configOne) ? '-' : $configOne['val'];
                $yiyuan_name = empty($yiyuanOne) ? '-' : $yiyuanOne['title'];
            }
            $arys[] = [
                'id' => $v['id'],
                'did' => $did,
                'uname' => $v['uname'],
                'uhead' => $head,
                'depart_name' => $depart_name,
                'work_title_name' => $work_title_name,
                'yiyuan_name' => $yiyuan_name,
                'price' => $price,
                'distance' => '3.3km',
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //医生详情
    public function doctorOne($did)
    {
        $res = (array) $this->dbConn($this->dbDoctor)
            ->where('id', $did)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('id', $res['uid'])
            ->first();
        $departOne = (array) $this->dbConn($this->dbCate)
            ->where('id', $res['depart'])
            ->first();
        $touxianOne = (array) $this->dbConn($this->dbCate)
            ->where('id', $res['work_title'])
            ->first();
//        $configOne = (array) $this->dbConn($this->dbUdSeek)
//            ->where('del', 0)
//            ->where('doctor_id', $res['id'])
//            ->first();
        $configOne = (array) $this->dbConn($this->dbConfig)
            ->where('del', 0)
            ->where('id', 1)
            ->first();
        $yiyuanOne = (array) $this->dbConn($this->dbYiyuan)
            ->where('id', $res['hospital'])
            ->first();
        $uname = empty($uOne) ? '-' : $uOne['uname'];
        $uhead = !empty($uOne)&&file_exists($uOne['head']) ? env('DOMAIN').'/'.$uOne['head'] : '';
        $depart_name = empty($departOne) ? '-' : $departOne['title'];
        $work_title_name = empty($touxianOne) ? '-' : $touxianOne['title'];
//        $price = empty($configOne) ? 0 : $configOne['price'];
        $price = empty($configOne) ? 0 : $configOne['val'];
        $yiyuan_name = empty($yiyuanOne) ? 0 : $yiyuanOne['title'];
        $yyList = $this->getYYtime($res['uid']);
        $ary = [
            'id' => $res['id'],
            'uname' => $uname,
            'uhead' => $uhead,
            'work_title_name' => $work_title_name,
            'depart_name' => $depart_name,
            'yiyuan_name' => $yiyuan_name,
            'price' => toNumber($price),
            'yyList' => $yyList,
        ];
        return $this->toback(0, '', $ary);
    }

    //预约时间
    public function getYYtime($uid)
    {
        $yyhour = date('Y-m-d H', time());
        $yyStart = strtotime($yyhour.':00:01');
        $yyStart = $yyStart<time() ? date('Y-m-d H', ($yyStart + 3600)) : $yyhour;
        $arys[] = ['title' => $yyStart, 'is_yy' => 0];
        $yyEnd = $yyStart;
        $yylen = 24;
        for ($i = 0; $i < $yylen; $i ++) {
            $yyH = date('Y-m-d H', (strtotime($yyEnd.':00:01') + 3600));
            $yyOne = (array) $this->dbConn($this->dbYihu)
                ->where('del', 0)
                ->where('did', $uid)
                ->where('yytime', $yyhour)
                ->first();
            $isyy = empty($yyOne) ? '' : '(已有预约)';
            if (count($arys) < $yylen) {
                $arys[] = [
                    'title' => $yyH.$isyy,
                    'is_yy' => empty($yyOne) ? 0 : 1,
                ];
                $yyEnd = $yyH;
            }
        }
        return $arys;
    }

    /**
     * 医护发布
     * @param array $pas
     * @param array $attrList
     */
    public function add($pas, $attrList)
    {
//        $ary = [
//            'uid' => $pas['uid'],
//            'yytime' => $pas['yytime'],
//            'yydizhi' => $pas['yydizhi'],
//            'price' => $pas['price'] * 100,
//            'addtime' => toDate(),
//        ];
//        $yytimeOne = (array) $this->dbConn($this->dbYihu)
//            ->where('yytime', $pas['yytime'])
//            ->first();
//        if (!empty($yytimeOne)) {
//            return $this->toback(-2, '该时间已被占用');
//        }
        DB::beginTransaction(); //开启事务
        try {
            $lastid = $this->dbConn($this->dbYihu)->insertGetId($pas);
            if (!$lastid) {
                return $this->toback(-1, 'error');
            }
            //属性集合处理
            $attrs = $attrList ? json_decode($attrList, true) : [];
            if (count($attrs)) {
                foreach ($attrs as $k => $v) {
                    $this->dbConn($this->dbYhAttr)->insertGetId([
                        'yhid' => $lastid, 'key' => $v['label'], 'val' => $v['value'], 'addtime' => toDate(),
                     //   'yhid' => $lastid, 'key' => $k, 'val' => $v, 'addtime' => toDate(),
                    ]);
                }
            }
            //广场处理
            $this->dbConn($this->dbGc)->insertGetId([
                'type' => 2, 'oid' => $lastid, 'addtime' => toDate(),
            ]);
            DB::commit(); //提交事务
            $ary = [
                'yw_type' => self::YwTypeGcYihu,
                'yw_id' => $lastid,
            ];
            return $this->toback(0, '', $ary);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return $this->toback(-1, 'error');
        }
    }


    /**
     * 列表
     * @param array $pages【start，limit】
     */
    public function getList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbYihu)
            ->where('del', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $v['did'])
                ->first();
            $uname = empty($uOne) ? '-' : $uOne['uname'];
            $arys[] = [
                'id' => $v['id'],
                'did' => $v['did'],
                'dname' => $uname,
                'yytime' => $v['yytime'],
                'yydizhi' => $v['yydizhi'],
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 医生接单
     * @param int $id
     * @param int $uid
     */
    public function doctorRob($id, $uid)
    {
        $res = (array) $this->dbConn($this->dbYihu)
            ->where('del', 0)
            ->where('did', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        if ($res['is_close']) {
            return $this->toback(-2, '已取消');
        }
        if ($res['status'] > 2) {
            return $this->toback(-2, '进行中');
        }
        $up = $this->dbConn($this->dbYihu)
            ->where('id', $id)
            ->update(['status' => 3, 'did' => $uid, 'robtime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        $patOne = (array) $this->dbConn($this->dbUser)
            ->where('id', $res['uid'])
            ->first();
        $arys = [
            'pat_phone' => !empty($patOne)&&$patOne['phone'] ? $patOne['phone'] : '',
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 病情评估
     * @param int $id
     */
    public function doctorSee($id)
    {
        $res = (array) $this->dbConn($this->dbYihu)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        if ($res['is_close']) {
            return $this->toback(-2, '已取消');
        }
        if ($res['status'] > 3) {
            return $this->toback(-2, '进行中');
        }
        $up = $this->dbConn($this->dbYihu)
            ->where('id', $id)
            ->update(['status' => 4, 'seetime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 上门服务
     * @param int $id
     */
    public function toDoor($id)
    {
        $res = (array) $this->dbConn($this->dbYihu)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        if ($res['is_close']) {
            return $this->toback(-2, '已取消');
        }
        if ($res['status'] > 4) {
            return $this->toback(-2, '进行中');
        }
        $up = $this->dbConn($this->dbYihu)
            ->where('id', $id)
            ->update(['status' => 4, 'doortime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 取消
     * @param int $id
     */
    public function toClose($id, $remark)
    {
        $res = (array) $this->dbConn($this->dbYihu)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        if ($res['is_close']) {
            return $this->toback(-2, '已取消');
        }
        if ($res['status'] > 4) {
            return $this->toback(-2, '进行中');
        }
        $up = $this->dbConn($this->dbYihu)
            ->where('id', $id)
            ->update(['is_close' => 1, 'close_remark' => $remark, 'closetime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 服务确认
     * @param int $id
     */
    public function toSure($id)
    {
        $res = (array) $this->dbConn($this->dbYihu)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        if ($res['is_close']) {
            return $this->toback(-2, '已取消');
        }
        if ($res['status'] > 5) {
            return $this->toback(-2, '进行中');
        }
        $up = $this->dbConn($this->dbYihu)
            ->where('id', $id)
            ->update(['status' => 6, 'finishtime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 患者预约
     */
    public function patYuyue($pas)
    {
        DB::beginTransaction(); //开启事务
        try {
            $res = (array)$this->dbConn($this->dbYihu)
                ->where('del', 0)
                ->where('did', $pas['did'])
                ->where('yytime', $pas['yytime'])
                ->first();
            if (!empty($res)) {
                return $this->toback(-2, '该医生当前时间已被预约');
            }
            $pas['addtime'] = $pas['robtime'] = toDate();
            $lastid = $this->dbConn($this->dbYihu)->insertGetId($pas);
            if (!$lastid) {
                return $this->toback(-1, 'error');
            }
            DB::commit(); //提交事务
            $ary = [
                'yw_type' => self::YwTypeGcYihu,
                'yw_id' => $lastid,
            ];
            return $this->toback(0, '', $ary);

        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return $this->toback(-1, 'error');
        }
    }

    /**
     * 小区医护价格
     * 通过类型获取
     */
    public function price($cate_id)
    {
        $arys = [
            'price' => 0,
        ];
        $res = (array) $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('type', 8)
            ->where('id', $cate_id)
            ->first();
        if (!empty($res) && $res['price']) {
            $arys['price'] = toNumber($res['price']);
        }
        return $this->toback(0, '', $arys);
    }

    /**
     * 医护详情
     * @param int $id
     */
    public function getOne($id)
    {
        $res = (array) $this->dbConn($this->dbYihu)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        //患者
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('id', $res['uid'])
            ->first();
        $uname = empty($uOne) ? '-' : $uOne['uname'];
        $uhead = !empty($uOne)&&file_exists($uOne['head']) ? env('DOMAIN').'/'.$uOne['head'] : '';
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'uname' => $uname,
            'uhead' => $uhead,
            'yytime' => $res['yytime'],
            'yydizhi' => $res['yydizhi'],
            'price' => toNumber($res['price']),
            'remark' => $res['remark'],
            'addtime' => $res['addtime'],
            'yy_map' => $res['yy_map'],
        ];
        return $this->toback(0, '', $arys);
    }
}